package com.jd.myaaaccount;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.location.LocationClientOption.LocationMode;
import com.jd.myaaaccount.entity.ConsumptionCategory;
import com.jd.myaaaccount.entity.DayBook;
import com.jd.myaaaccount.entity.Family;
import com.jd.myaaaccount.entity.Host;
import com.jd.myaaaccount.entity.Location;
import com.jd.myaaaccount.model.Common;
import com.jd.myaaaccount.model.DayBookModel;
import com.jd.myaaaccount.model.FamilyModel;
import com.jd.myaaaccount.model.UserModel;
import com.jd.myaaaccount.util.AlertDialogHelper;
import com.jd.myaaaccount.util.ErrorCode;
import com.jd.myaaaccount.util.OperateCode;

public class AddDayBookPage extends BasePage {

	private EditText etMoney;
	private TextView tvHome;
	private TextView tvType;
	private TextView tvConsumer;
	private TextView tvDate;
	private EditText etRemark;
	private TextView tvLocation;
	private ImageView ivAddPicture;
	private Button btnSave;

	private UserModel um;
	private FamilyModel fm;
	private DayBookModel dm;

	private List<Family> families;
	private List<ConsumptionCategory> categories;
	private List<Host> customers;

	private Handler handler;
	private int flag;// 0表示个人消费 1表示家庭消费
	private Family selectedFamily;
	private ConsumptionCategory selectedCategory;
	private Date selectedDate;

	// 消费人员
	private boolean[] selectedConsumers;
	private String[] consumers;
	private OnClickListener consumerClickListener;

	// 地理位置
	double lat;// 坐标
	double lng;// 坐标
	String address;// 地址
	String detailAddress;// 详细地址
	String description;// 描述
	String[] pois;// 可选地点
	int selectPoiIndex = -1;// 选择的点
	// 最多定位次数
	int locateTime = 3;

	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();

	private byte[] bmpDatas;

	@Override
	public void iniPage(Activity context) {
		super.iniPage(context);

		initControl();

		um = new UserModel(context);
		fm = new FamilyModel(context);
		dm = new DayBookModel(context);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (pd != null)
					pd.cancel();
				switch (msg.what) {
				case OperateCode.GET_FAMILY:// 家庭列表
					if (msg.arg1 == ErrorCode.SUCCESS) {
						families = (List<Family>) msg.obj;
						Family f = new Family();// 自己作为虚拟家庭
						f.setId(Common.currentUser.getId());
						f.setName(Common.currentUser.getName());
						families.add(0, f);
						String[] familiesName = new String[families.size()];
						for (int i = 0; i < families.size(); i++) {
							familiesName[i] = families.get(i).getName();
						}
						ArrayAdapter<String> homeAdapter = new ArrayAdapter<String>(
								AddDayBookPage.this.context,
								android.R.layout.simple_spinner_dropdown_item,
								familiesName);
						// spHome.setAdapter(homeAdapter);
					} else {
						Common.showErrorInfo(AddDayBookPage.this.context,
								msg.arg1, "加载失败", 0);
					}
					break;
				case OperateCode.GET_CATEGORY:// 消费类别列表
					if (msg.arg1 == ErrorCode.SUCCESS) {
						categories = (List<ConsumptionCategory>) msg.obj;
						String[] categriesName = new String[categories.size()];
						for (int i = 0; i < categories.size(); i++) {
							categriesName[i] = categories.get(i).getName();
						}
						ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(
								AddDayBookPage.this.context,
								android.R.layout.simple_spinner_dropdown_item,
								categriesName);
						// spType.setAdapter(typeAdapter);
					} else {
						Common.showErrorInfo(AddDayBookPage.this.context,
								msg.arg1, "加载失败", 0);
					}
					break;
				case OperateCode.LOCATION:
					if (msg.arg1 == ErrorCode.SUCCESS) {
						BDLocation location = (BDLocation) msg.obj;
						lat = location.getLatitude();
						lng = location.getLongitude();

						address = location.getDistrict() + " "
								+ location.getStreet();
						detailAddress = location.getAddrStr();
						description = location.getLocationDescribe();
						List<Poi> ps = location.getPoiList();
						selectPoiIndex = -1;
						if (ps == null) {
							pois = null;
						} else {
							pois = new String[ps.size()];
							for (int i = 0; i < pois.length; i++) {
								pois[i] = ps.get(i).getName();
							}
						}
					} else {
						lat = 0;
						lng = 0;
					}
					showDetailAddress();
					break;
				case OperateCode.ADD:
					if (msg.arg1 == ErrorCode.SUCCESS) {
						new AlertDialog.Builder(AddDayBookPage.this.context)
								.setTitle("提示")
								.setMessage("保存成功")
								.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface arg0,
													int arg1) {
											};
										}).show();
						etMoney.setText("");
						etRemark.setText("");
						bmpDatas = null;
						((ImageView) AddDayBookPage.this.context
								.findViewById(R.id.ivPiture1))
								.setImageBitmap(null);
					} else if (msg.arg1 == ErrorCode.TOKEN_OVERDUE) {
						Common.loginTimeOut(AddDayBookPage.this.context);
					} else {
						AlertDialogHelper.showOKAlertDialog(
								AddDayBookPage.this.context, "保存失败");
					}
					break;
				default:
					break;
				}
			};
		};

		consumerClickListener = new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Builder builder = new AlertDialog.Builder(
						AddDayBookPage.this.context);
				builder.setTitle("消费人员");
				builder.setMultiChoiceItems(consumers, selectedConsumers,
						new OnMultiChoiceClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1,
									boolean arg2) {
								selectedConsumers[arg1] = arg2;
							}
						});
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								String temp = "";
								for (int i = 0; i < selectedConsumers.length; i++) {
									if (selectedConsumers[i])
										temp += consumers[i] + "  ";
								}
								// etConsumer.setText(temp);
							}
						});
				builder.create().show();
			}
		};

		tvLocation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (pois == null || pois.length <= 0)
					return;
				Builder builder = new AlertDialog.Builder(
						AddDayBookPage.this.context);
				builder.setTitle("位置");

				builder.setSingleChoiceItems(pois, selectPoiIndex,

				new AlertDialog.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						selectPoiIndex = arg1;
					}
				});
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								showDetailAddress();
							}
						});
				builder.create().show();
			}
		});

		ivAddPicture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(AddDayBookPage.this.context,
						CaptureActivity.class);

				AddDayBookPage.this.context.startActivityForResult(intent,
						OperateCode.CAPTURE);
			}
		});
		iniFamily();
		initLocation();
	}

	private void initControl() {
		etMoney = (EditText) context.findViewById(R.id.etMoney);
		tvHome = (TextView) context.findViewById(R.id.tvHome);
		tvType = (TextView) context.findViewById(R.id.tvType);
		tvConsumer = (TextView) context.findViewById(R.id.tvConsumer);
		tvDate = (TextView) context.findViewById(R.id.tvDate);
		etRemark = (EditText) context.findViewById(R.id.etRemark);
		tvLocation = (TextView) context.findViewById(R.id.tvLocation);
		ivAddPicture = (ImageView) context.findViewById(R.id.ivAddPicture);
		btnSave = (Button) context.findViewById(R.id.btnSave);
		// spHome.setOnItemSelectedListener(new OnItemSelectedListener() {
		// @Override
		// public void onItemSelected(AdapterView<?> arg0, View arg1,
		// int arg2, long arg3) {
		// selectedFamily = families.get(arg2);
		// flag = arg2 == 0 ? 0 : 1;
		// // 初始化消费类别
		// iniTypeList(selectedFamily, flag);
		// // 初始化家庭成员
		// iniMemberList(selectedFamily, flag);
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		//
		// }
		// });

		// spType.setOnItemSelectedListener(new OnItemSelectedListener() {
		// @Override
		// public void onItemSelected(AdapterView<?> arg0, View arg1,
		// int arg2, long arg3) {
		// selectedCategory = categories.get(arg2);
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		//
		// }
		// });

		selectedDate = new Date();

		tvDate.setText(DateFormat.getDateInstance().format(selectedDate));
		tvDate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Calendar c = Calendar.getInstance();
				if (selectedDate == null) {
					c.setTime(new Date());
				} else {
					c.setTime(selectedDate);
				}
				DatePickerDialog dpd = new DatePickerDialog(
						AddDayBookPage.this.context, new OnDateSetListener() {
							@Override
							public void onDateSet(DatePicker arg0, int arg1,
									int arg2, int arg3) {
								tvDate.setText(String.format("%d-%d-%d", arg1,
										arg2 + 1, arg3));
								Calendar c = Calendar.getInstance();
								c.set(arg1, arg2, arg3);
								selectedDate = c.getTime();
							}

						}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c
								.get(Calendar.DAY_OF_MONTH));
				dpd.show();
			}
		});

		btnSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				save();
			}
		});
	}

	/**
	 * 初始化家庭
	 */
	private void iniFamily() {
		pd = AlertDialogHelper.showWaitProgressDialog(context, "加载中…");
		new Thread(new Runnable() {
			@Override
			public void run() {
				fm.getMyFamily(handler);
			}
		}).start();
	}

	/**
	 * 初始化类别列表
	 * 
	 * @param obj
	 *            家庭
	 */
	private void iniTypeList(final Family host, final int flag) {
		pd = AlertDialogHelper.showWaitProgressDialog(context, "加载中…");
		new Thread(new Runnable() {

			@Override
			public void run() {
				if (flag == 0)
					um.getCategory(host.getId(), handler);
				else
					fm.getCategory(host.getId(), handler);
			}
		}).start();

	}

	/**
	 * 初始化家庭成员列表
	 * 
	 * @param obj
	 *            家庭
	 */
	private void iniMemberList(Family family, int flag) {
		if (flag == 0) { // 消费人员设置为自己
			tvConsumer.setText(Common.currentUser.getName());
			tvConsumer.setOnClickListener(null);
		} else {
			customers = family.getMembers();
			tvConsumer.setText("");
			consumers = new String[customers.size()];
			selectedConsumers = new boolean[customers.size()];
			for (int i = 0; i < customers.size(); i++) {
				consumers[i] = customers.get(i).getName();
			}
			tvConsumer.setOnClickListener(consumerClickListener);
		}
	}

	private void initLocation() {
		mLocationClient = new LocationClient(context.getApplicationContext());
		mLocationClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);
		option.setCoorType("bd09ll");
		int span = 3000;
		option.setScanSpan(span);
		option.setIsNeedAddress(true);
		option.setOpenGps(true);
		option.setLocationNotify(true);
		option.setIsNeedLocationDescribe(true);
		option.setIsNeedLocationPoiList(true);
		option.setIgnoreKillProcess(false);
		option.SetIgnoreCacheException(false);
		option.setEnableSimulateGps(false);
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}

	/**
	 * 显示详细地址信息
	 */
	private void showDetailAddress() {
		StringBuilder sb = new StringBuilder();
		if (lat == 0) {
			sb.append("定位失败");
		} else {
			sb.append(detailAddress);
			if (selectPoiIndex >= 0) {
				sb.append(" " + pois[selectPoiIndex]);
			} else {

				sb.append("(" + description + ")");
			}
		}
		tvLocation.setText(sb.toString());
	}

	/**
	 * 显示选择的图片
	 */
	public void setPiture(Uri uri) {
		// if (uri == null)
		// return;
		// Bitmap bmp = getBitmapFromUrl(uri, 150, 150);
		// if (bmp != null) {
		// ((ImageView) context.findViewById(R.id.ivPiture1 + bmpIndex))
		// .setImageBitmap(bmp);
		// bmpIndex++;
		// }
	}

	/**
	 * 显示拍摄的图片
	 */
	public void setPiture(byte[] arg0) {
		if (arg0 == null)
			return;
		bmpDatas = arg0;
		ImageView tempIV = ((ImageView) context.findViewById(R.id.ivPiture1));
		Bitmap bmp = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
		tempIV.setImageBitmap(bmp);
		tempIV.setVisibility(View.VISIBLE);
	}

	/**
	 * 保存
	 */
	private void save() {
		if (etMoney.getText().toString().equals("")) {
			Toast.makeText(context, "消费金额不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		double money = 0.00;

		try {
			money = Double.valueOf(etMoney.getText().toString());
			money = Common.convertDouble(money, 2);
		} catch (NumberFormatException e) {
			Toast.makeText(context, "消费金额格式错误", Toast.LENGTH_SHORT).show();
			return;
		}

		final DayBook daybook = new DayBook();
		daybook.setMoney(money);
		daybook.setCreator(Common.currentUser);
		daybook.setPayer(Common.currentUser);
		daybook.setCategory(selectedCategory);
		daybook.setFlag(flag);
		daybook.setHost(new Host(selectedFamily));
		List<Host> selectedCustomers = new ArrayList<Host>();
		if (flag == 0) {
			selectedCustomers.add(Common.currentUser);
		} else {
			for (int i = 0; i < selectedConsumers.length; i++) {
				if (selectedConsumers[i]) {
					selectedCustomers.add(customers.get(i));
				}
			}
		}
		daybook.setCustomers(selectedCustomers);
		daybook.setSettled(0);
		daybook.setDate(selectedDate);// 消费日期
		daybook.setDescription(etRemark.getText().toString());
		Location location = new Location();
		location.setAddress(address);
		location.setDetailAddress(tvLocation.getText().toString());
		location.setLatitude(lat);
		location.setLongitude(lng);
		daybook.setLocation(location);

		pd = AlertDialogHelper.showWaitProgressDialog(context, "保存中…");
		new Thread(new Runnable() {

			@Override
			public void run() {
				List<String> files = new ArrayList<String>();
				Random rand = new Random(new Date().getTime());

				String basefilename = String.valueOf(daybook.getCreator()
						.getNumber())
						+ "_"
						+ String.valueOf(daybook.getHost().getNumber())
						+ "_"
						+ String.valueOf(rand.nextInt(100000)) + "_1.jpg";
				if (bmpDatas != null) {// 上传图片
					String res = dm.uploadPicture(bmpDatas, basefilename);
					if (res.equals(basefilename)) {
						files.add(basefilename);
					} else {
						Message msg = Message.obtain(handler, OperateCode.ADD,
								ErrorCode.FAIL, 0);
						msg.sendToTarget();
						return;
					}
				}
				daybook.setPictures(files);
				dm.add(daybook, handler);
			}
		}).start();
	}

	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation arg0) {
			locateTime--;
			if (arg0.getLocType() == BDLocation.TypeGpsLocation
					|| arg0.getLocType() == BDLocation.TypeNetWorkLocation) {

				Message msg2 = Message.obtain(handler, OperateCode.LOCATION,
						ErrorCode.SUCCESS, 0, arg0);
				msg2.sendToTarget();
				mLocationClient.stop();
			} else {
				if (locateTime <= 0) {
					Message msg2 = Message.obtain(handler,
							OperateCode.LOCATION, ErrorCode.FAIL, 0, arg0);
					msg2.sendToTarget();
					mLocationClient.stop();
				}
			}
		}
	}
}
